/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.gwt.client.sec.content.group;

import han.bifang.gwt.client.common.RequestObject;
import han.bifang.gwt.client.common.ResponseObject;
import han.bifang.gwt.client.common.entity.Role;
import han.bifang.gwt.client.common.util.StringUtils;
import han.bifang.gwt.client.communicate.BifangGWTServiceAsync;
import han.bifang.gwt.client.sec.CustomCheckBox;
import han.bifang.gwt.client.sec.SecurityMessages;

import java.util.ArrayList;
import java.util.HashMap;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.HTMLTable.ColumnFormatter;

/**
 * 
 * @Author Kent
 */
public class SearchRolePanel extends Composite {

	private SecurityMessages cons = null;

	private BifangGWTServiceAsync service = null;

	private VerticalPanel panel;

	private SimplePanel result = null;

	private TextBox roleName;

	private CustomCheckBox[] checks;

	private int size = 10;

	private int currentPage = 1;

	private DialogBox box;

	private RoleAndUserSearcher searcher;
	
	private String groupId;
	
	private boolean loaded ;

	private AsyncCallback<ResponseObject> cb = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (!code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}

			ArrayList ret = (ArrayList) res.getResponse();
			int total = (Integer) ret.get(0);
			// Window.alert("total " + total);
			ArrayList list = (ArrayList) ret.get(1);
			if (total != 0) {
				VerticalPanel v = new VerticalPanel();
				v.setWidth("100%");
				v.setSpacing(5);

				Grid table = new Grid(list.size() + 1, 3);
				table.setWidth("100%");
				table.setCellPadding(1);
				table.setCellSpacing(1);
				table.setBorderWidth(1);

				ColumnFormatter cf = table.getColumnFormatter();

				cf.setWidth(0, "15%");
				cf.setWidth(1, "25%");
				cf.setWidth(2, "55%");

				CellFormatter ff = table.getCellFormatter();
				ff.setStyleName(0, 0, "tablecol");
				ff.setStyleName(0, 1, "tablecol");
				ff.setStyleName(0, 2, "tablecol");

				table.setHTML(0, 0, "&nbsp");
				table.setHTML(0, 1, cons.roleName());
				table.setHTML(0, 2, cons.description());
				
				checks = new CustomCheckBox[list.size()];
				for (int i = 1, j = list.size() + 1; i < j; i++) {
					Role s = (Role) list.get(i - 1);
					checks[i - 1] = new CustomCheckBox();
					checks[i - 1].setProperties(s);
					table.setWidget(i, 0, checks[i - 1]);
					table.setHTML(i, 1, s.getRoleName());
					table.setHTML(i, 2, s.getDescription());

				}
				v.add(table);
				v.add(new HTML("&nbsp;"));
				HorizontalPanel h = new HorizontalPanel();
				h.setWidth("60%");
				h.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
				h.add(new HTML(cons.page(total, currentPage)));
				v.add(h);
				if (total > 1) {

					if (currentPage > 1) {
						Button pre = new Button(cons.previous());
						pre.addClickListener(new ClickListener() {
							public void onClick(Widget sender) {
								currentPage--;
								searchRole(currentPage, size);
							}

						});
						// h.add(new HTML("&nbsp;&nbsp;"));
						h.add(pre);
					}
					if (currentPage < total) {
						Button n = new Button(cons.next());
						n.addClickListener(new ClickListener() {
							public void onClick(Widget sender) {
								currentPage++;
								searchRole(currentPage, size);
							}

						});
						// h.add(new HTML("&nbsp;&nbsp;"));
						h.add(n);

					}

				}
				result.setWidget(v);

			}else{
				result.setWidget(new HTML(cons.noResult()));
			}
		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	public SearchRolePanel(SecurityMessages cons,
			BifangGWTServiceAsync service, DialogBox box, String groupId) {
		this.service = service;
		this.cons = cons;
		this.box = box;
		this.groupId = groupId;
		panel = new VerticalPanel();
		initWidget(panel);

	}

	public void onLoad() {
		if(!loaded){
		Grid table = new Grid(2, 2);
		table.setWidth("100%");
		table.setCellPadding(1);
		table.setCellSpacing(1);
		table.setBorderWidth(1);

		ColumnFormatter cf = table.getColumnFormatter();
		cf.setWidth(0, "33%");
		cf.setWidth(1, "33%");

		CellFormatter ff = table.getCellFormatter();
		ff.setStyleName(0, 0, "tablecol");
		ff.setStyleName(0, 1, "tablecol");

		table.setHTML(0, 0, cons.roleName());
		table.setHTML(0, 1, "&nbsp;");

		roleName = new TextBox();
		roleName.setVisibleLength(32);

		Button search = new Button(cons.search());
		search.addClickListener(new ClickListener() {

			public void onClick(Widget sender) {
				searchRole(currentPage, size);

			}
		});

		table.setWidget(1, 0, roleName);
		table.setWidget(1, 1, search);

		panel.add(table);
		panel.add(new HTML("&nbsp;"));
		result = new SimplePanel();
		panel.add(result);

		searchRole(currentPage, size);

		HorizontalPanel h = new HorizontalPanel();
		Button add = new Button(cons.addRole());

		add.addClickListener(new ClickListener() {

			public void onClick(Widget sender) {
				box.hide();
				ArrayList<Role> ret = new ArrayList<Role>();
				for (CustomCheckBox check : checks) {
					if (check.isChecked()) {
						Role gg = (Role) check.getProperties();
						ret.add(gg);
					}
				}
				searcher.onRoleSearchResult(ret);

			}

		});

		Button ret = new Button(cons.cancel());
		ret.addClickListener(new ClickListener() {

			public void onClick(Widget sender) {
				box.hide();

			}

		});
		h.add(add);
		h.add(new HTML("&nbsp;&nbsp"));
		h.add(ret);
		
		panel.add(new HTML("&nbsp;"));
		panel.add(h);
		 loaded = true;
		}

	}

	private void searchRole(int page, int size) {
		RequestObject req = new RequestObject();
		req
				.setAction("han.bifang.gwt.server.action.group.SearchRolesNotOfGroupAction");
		ArrayList p = new ArrayList();
		HashMap<String, String> param = new HashMap<String, String>();
		if (!StringUtils.isEmpty(roleName.getText()))
			param.put("roleName", roleName.getText());
		param.put("groupId", groupId);
		p.add(param);
		p.add(page);
		p.add(size);
		req.setRequest(p);
		service.call(req, cb);
	}

	public void setSearcher(RoleAndUserSearcher searcher) {
		this.searcher = searcher;
	}

}
